<?php

function get_countries_list() {
  $countries = array();
  $query = 'select countryid, country from countries order by country';
  $result = db_query($query);
  if (!$result) {
    die(drupal_set_message("Error talking to database."));
  } else {
    while ($obj = db_fetch_object($result)) {
      //$countries[] = array('id' => $obj->countryid, 'name' => $obj->country);
      $countries[$obj->countryid] = t($obj->country);
    }
  }
  return $countries;
}

function get_regions_for_country($params) {
  $countryid = $params['countryid'];

  if (empty($countryid) || $countryid == null) {
    die(json_encode(set_error_arr("Required parameters missing.")));
  }

  $response = array();

  $query = "select regionid, region from regions where countryid = %d order by region";
  $query_args = array($countryid);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error talking to database.")));
  } else {
    $regions = array();
    while ($obj = db_fetch_object($result)) {
      //$regions[] = array('id' => $obj->regionid, 'name' => $obj->region);
      $regions[$obj->regionid] = t($obj->region);
    }
    $response = set_no_error_arr("");
    $response['regions'] = $regions;
  }

  die(json_encode($response));
}

function get_cities_for_region($params) {
  $regionid = $params['regionid'];

  if (empty($regionid) || $regionid == null) {
    die(json_encode(set_error_arr("Required parameters missing.")));
  }

  $response = array();

  $query = "select cityid, city from cities where regionid = %d order by city";
  $query_args = array($regionid);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error talking to database.")));
  } else {
    $cities = array();
    while ($obj = db_fetch_object($result)) {
      //$cities[] = array('id' => $obj->cityid, 'name' => $obj->city);
      $cities[$obj->cityid] = t($obj->city);
    }
    $response = set_no_error_arr("");
    $response['cities'] = $cities;
  }

  die(json_encode($response));
}

function get_part_of_day_options() {
  $options = array();
  $query = 'select id, label from partofday order by id';
  $result = db_query($query);
  if (!$result) {
    die(drupal_set_message("Error talking to database."));
  } else {
    while ($obj = db_fetch_object($result)) {
      //$countries[] = array('id' => $obj->countryid, 'name' => $obj->country);
      $options[$obj->id] = t($obj->label);
    }
  }
  return $options;
}

function get_synonym_reasons() {
  $reasons = array();
  $query = 'select id, status from win_statuses order by status';
  $result = db_query($query);
  if (!$result) {
    die(drupal_set_message("Error talking to database."));
  } else {
    while ($obj = db_fetch_object($result)) {
      //$countries[] = array('id' => $obj->countryid, 'name' => $obj->country);
      $reasons[$obj->id] = t($obj->status);
    }
  }
  return $reasons;
}

function delete_observation($data) {
  $oid = $data['observation_id'];
  $query = 'select created_by from win_observations where id = %d';
  $query_args = array($oid);
  $result = db_query($query, $query_args);
  if (!$result) {
  }
  else {
    if ($obj = db_fetch_object($result)) {
      $created_by = $obj->created_by;
      global $user;
      if ((int)$user->uid == (int)$obj->created_by) {
        clear_observations_partofday($oid);
        clear_location_info($oid);
        clear_scientific_name($oid);
        clear_common_names($oid);
        clear_observation_image_mapping($oid);
        clear_observation($oid);
      }
    }
  }
}

function clear_observation($oid) {
  $query = 'delete from win_observations where id = %d';
  $query_args = array($oid);
  $result = db_query($query, $query_args);
  if (!$result) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

function save_observation($data) {
  if (!win_observation_user_has_edit_permissions()) {
    die(json_encode(set_error_arr("You are not authorized.")));
  }

  if ($_SESSION['win_captcha_code'] != $data['captcha']) {
    die(json_encode(set_error_arr("The string entered does not match the captcha image.")));
  }

  global $user;
  $userid = $user->uid;

  $observation_args = array();
  $pod_args = array();
  $location = array();
  $common_names = array();

  $observation_id = $data['observation_id'];

  $common_names = $data['common_names'];

  $scientific_name_info = $data['scientific_name_info'];
  //$observation_args['s_taxa'] = $data['s_taxa'];
  $observation_args['s_kingdom'] = utf8_encode($data['s_kingdom']);
  $observation_args['s_phylum'] = utf8_encode($data['s_phylum']);
  $observation_args['s_class'] = utf8_encode($data['s_class']);
  $observation_args['s_order'] = utf8_encode($data['s_order']);
  $observation_args['s_family'] = utf8_encode($data['s_family']);
  $observation_args['s_genus'] = utf8_encode($data['s_genus']);
  $observation_args['s_species'] = utf8_encode($data['s_species']);

  $observation_args['taxanomic_status'] = utf8_encode($data['taxanomic_status']);
  $observation_args['nomenclature_type_status'] = utf8_encode($data['nomenclature_type_status']);

  $observation_args['ecosystem_id'] = $data['ecosystem_id'];
  $observation_args['nativeness'] = $data['nativeness'];
  $observation_args['iucn_threat_category'] = $data['iucn_threat_category'];

  // $observation_args['gender'] = $data['gender'];
  // $observation_args['lifestage'] = $data['lifestage'];
  $observation_args['num_individuals'] = $data['num_individuals'];

  $is_date_range = $data['is_date_range'];
  $observation_args['is_date_range'] = $is_date_range;
  if ($is_date_range) {
    $observation_args['from_date'] = $data['from_date'];
    $observation_args['to_date'] = $data['to_date'];
  } else {
    $observation_args['on_date'] = $data['on_date'];
  }

  $is_exact_time = $data['is_exact_time'];
  $observation_args['is_exact_time'] = $is_exact_time;
  if ($is_exact_time) {
    $observation_args['at_time'] = $data['at_time'];
  } else {
    if (!empty($data['pod'])) {
      $pod_args = explode(",", $data['pod']);
    }
  }

  $observation_args['altitude'] = $data['altitude'];
  $observation_args['depth'] = $data['depth'];

  $is_waterbody_related = $data['is_waterbody_related'];
  $observation_args['is_waterbody_related'] = $is_waterbody_related;
  if ($is_waterbody_related) {
    $observation_args['waterbody_type'] = $data['waterbody_info']['type'];
    $observation_args['waterbody_name'] = $data['waterbody_info']['name'];
  }
  else {
    $observation_args['waterbody_type'] = '';
    $observation_args['waterbody_name'] = '';
  }

  $observer_type = $data['observer']['type'];
  $observer_id = 0;
  if ($observer_type == 0) {
    $observer_id = get_current_user_observerid();
  } elseif ($observer_type == 1) {
    $observer_id = $data['observer']['id'];
    if ($observer_id == 0) {
      $observer_details = $data['observer']['details'];
      $observer_id = save_observer_details($observer_details);
      if (strpos($observer_id, 'Error:') === 0) {
        die(json_encode(set_error_arr($observer_id)));
      }
    }
    /*
    if ($observer_id > 0) {
      $observation_args['observer_id'] = $observer_id;
    }
    */
  }
  $observation_args['observer_id'] = $observer_id;
  $observation_args['basis_of_record'] = $data['basis_of_record'];

  $observation_args['record_language'] = $data['record_language'];
  $observation_args['comments'] = $data['comments'];

  $observation_args['topology'] = $data['topology'];

  $location = $data['location'];

  if ($observation_id == 0) {
    $observation_id = insert_observation_record($observation_args, $pod_args, $location, $common_names, $scientific_name_info);
    $imgs_url = base_path() . 'observation/'.$observation_id.'/images';
    $rec_url = base_path() . 'observation/add';
    //display_message('status', t('Thank you for contributing to Spandan. Your data still needs to be validated and marked as verfied. It will be displayed only after validation. To upload more images click <a href="'.$imgs_url.'">here</a> OR click <a href="'.$rec_url.'">here</a> to contribute more records.'));
    $output = set_no_error_arr("Record saved.");
    $output['observation_id'] = $observation_id;
    die(json_encode($output));
  }
  else {
    $query = 'update win_observations set ';
    $set_arr = array();
    foreach ($observation_args as $key => $value) {
      $set_arr[] = "$key = '%s'";
    }
    $set_arr[] = "modified_by = $userid";
    $set_arr[] = "modified_date = now()";
    $query .= implode(',', $set_arr);
    $query .= 'where id = %d';
    $result = db_query($query, array_merge(array_values($observation_args), (array)$observation_id));
    if (!$result) {
      die(json_encode(set_error_arr("Error saving record.")));
    } else {
        save_observations_partofday($observation_id, $pod_args);
        save_location_info($observation_id, $location);
        save_scientific_name($observation_id, $scientific_name_info);
        save_common_names($observation_id, $common_names);
      }

      if (isset($data['validation'])) {
        if (!update_observation_validation_status($observation_id, $data['validation'])) {
          die(json_encode(set_error_arr("Error saving record.")));
        }
      }

      if (!isset($data['validation'])) {
        // Clear the validated status for an observation when updated.
        $query = 'delete from win_validation where observation_id = %d and status = 1';
        $query_args = array($observation_id);
        $result = db_query($query, $query_args);
      }

      display_message('status', t('Your data has been updated.'));
      $output = set_no_error_arr("Record saved.");
      $output['observation_id'] = $observation_id;
      die(json_encode($output));
  }
  /*
  $commonnames = $data['commonnames'];
  foreach ($commonnames as $commonname) {
  }
  echo $data['commonnames'][0]['name'];
  */
}

function update_observation_validation_status($observation_id, $validation) {
  global $user;
  $id = 0;
  $query = "select id from win_validation where observation_id = %d and validated_by = %d";
  $query_args = array($observation_id, $user->uid);
  $result = db_query($query, $query_args);
  if (!$result) {
  }
  else {
    if ($obj = db_fetch_object($result)) {
      $id = $obj->id;
    }
  }

  if ($id == 0) {
    $query = "insert into win_validation (observation_id, status, comments, validated_by, validated_date) values (%d, %d, '%s', %d, now())";
    $query_args = array($observation_id, $validation['status'], $validation['comments'], $user->uid);
  }
  else {
    $query = "update win_validation set status = %d, comments = '%s', validated_date = now() where id = %d";
    $query_args = array($validation['status'], $validation['comments'], $id);
  }

  $result = db_query($query, $query_args);
  if (!$result) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

function insert_observation_record($observation_args, $pod_args, $location, $common_names, $scientific_name_info = NULL) {
  $keys = array_keys($observation_args);
  global $user;
  $userid = $user->uid;
  $query = 'insert into win_observations (' . implode(', ', $keys) . ', created_by, created_date, modified_by, modified_date) ';
  $query .= 'values (' . get_query_values_holder(array_values($observation_args)) . ', '.$userid.', now(), '.$userid.', now())';
  $result = db_query($query, array_values($observation_args));
  if (!$result) {
    die(json_encode(set_error_arr("Error saving record.")));
  } else {
    $query = 'select last_value from win_observations_id_seq';
    $result = db_query($query);
    if (!$result) {
      die(json_encode(set_error_arr("Error getting saved observation id.")));
    } else {
      if ($obj = db_fetch_object($result)) {
        $observation_id = $obj->last_value;

        save_observations_partofday($observation_id, $pod_args);
        save_location_info($observation_id, $location);
        if ($scientific_name_info != NULL) {
          save_scientific_name($observation_id, $scientific_name_info);
        }
        save_common_names($observation_id, $common_names);
      } else {
        die(json_encode(set_error_arr("Error getting saved observation id.")));
      }
    }

    /*
    display_message('status', t('Thank you for contributing to Spandan. Your data still needs to be validated and marked as verfied.'));
    $output = set_no_error_arr("Record saved.");
    $output['observation_id'] = $observation_id;
    die(json_encode($output));
    */
    return $observation_id;
  }
}

function clear_observations_partofday($observation_id) {
  $query = 'delete from win_observations_partofday where observation_id = %d';
  $query_args = array($observation_id);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error talking to database.")));
  }
}

function save_observations_partofday($observation_id, $pods) {
  clear_observations_partofday($observation_id);

  foreach ($pods as $pod_id) {
    $query = 'insert into win_observations_partofday(observation_id, pod_id) values (%d, %d);';
    $query_args = array($observation_id, $pod_id);
    $result = db_query($query, $query_args);
    if (!$result) {
      die(json_encode(set_error_arr("Error talking to database.")));
    }
  }
}

function clear_scientific_name($observation_id) {
  $query = 'delete from win_scientific_name where observation_id = %d';
  $query_args = array($observation_id);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error talking to database.")));
  }
}

function save_scientific_name($observation_id, $scientific_name_info) {
  clear_scientific_name($observation_id);

  $query = "insert into win_scientific_name (observation_id, s_name, s_author, s_year) values (%d, '%s', '%s', %d)";
  $query_args = array($observation_id, $scientific_name_info['s_name'], $scientific_name_info['s_author'], (int)$scientific_name_info['s_year']);
  $result = db_query($query, $query_args);
}

function clear_common_names($observation_id) {
  $query = 'delete from win_common_names where observation_id = %d';
  $query_args = array($observation_id);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error talking to database.")));
  }
}

function save_common_names($observation_id, $common_names) {
  clear_common_names($observation_id);

  foreach($common_names as $common_name_info) {
    $query = "insert into win_common_names (observation_id, common_name, cn_language, region, gender, lifestage, common_name_english) ";
    $query .= "values (%d, '%s', '%s', '%s', '%s', '%s', '%s')";
    $query_args = array($observation_id, $common_name_info['name'], $common_name_info['language'], $common_name_info['region'], $common_name_info['gender'], $common_name_info['lifestage'], $common_name_info['name_english']);
    $result = db_query($query, $query_args);
  }
}

function clear_location_info($observation_id) {
  $query = "delete from win_observation_location where observation_id = %d";
  $query_args = array($observation_id);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error talking to database.")));
  }
}

function save_location_info($observation_id, $location) {
  clear_location_info($observation_id);

  $query = "insert into win_observation_location (observation_id, country, region, city, locality) ";
  $query .= "values (%d, '%s', '%s', '%s', '%s')";
  $query_args = array($observation_id, $location['country'], $location['region'], $location['city'], $location['locality']);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error talking to database.")));
  }
}

function get_observers_list() {
  $observers = array();
  $query = "select id, coalesce(fname, '') || ' ' || coalesce(lname, '') as name from win_observer order by id";
  $result = db_query($query);
  if (!$result) {
    die(drupal_set_message("Error talking to database."));
  } else {
    while ($obj = db_fetch_object($result)) {
      //$countries[] = array('id' => $obj->countryid, 'name' => $obj->country);
      $observers[$obj->id] = t($obj->name);
    }
  }
  return $observers;
}

function get_observer_details($params) {
  $observer_id = $params['observer_id'];

  if (empty($observer_id) || $observer_id == null) {
    die(json_encode(set_error_arr("Required parameters missing.")));
  }

  $response = array();

  $query = "select * from win_observer where id = %d";
  $query_args = array($observer_id);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error talking to database.")));
  } else {
    $observer_details = array();
    if ($obj = db_fetch_object($result)) {
      //$regions[] = array('id' => $obj->regionid, 'name' => $obj->region);
      $observer_details['fname'] = t($obj->fname);
      $observer_details['lname'] = t($obj->lname);
      $observer_details['affiliation'] = t($obj->affiliation);
      $observer_details['address'] = t($obj->address);
      $observer_details['mobile'] = t($obj->mobile);
      $observer_details['phoneno'] = t($obj->phoneno);
      $observer_details['email'] = t($obj->email);
    }
    $response = set_no_error_arr("");
    $response['observer_details'] = $observer_details;
  }

  die(json_encode($response));
}

function save_observer_details($details) {
  $fname = $details['fname'];
  $lname = $details['lname'];
  $affiliation = $details['affiliation'];
  $address1 = $details['address1'];
  $address2 = $details['address2'];
  $city = $details['city'];
  $region = $details['region'];
  $country = $details['country'];
  $mobile = $details['mobile'];
  $phoneno = $details['phoneno'];
  $email = $details['email'];

  $id = 0;
  $query = "select id, fname || ' ' || lname as name from win_observer where email = '{$email}'";
  $result = db_query($query);
  if (!$result) {
  } else {
    if ($obj = db_fetch_object($result)) {
      $id = $obj->id;
      $name = $obj->name;
    }
  }

  if ($id == 0) {
    $query = 'insert into win_observer (fname, lname, affiliation, address1, address2, city, region, country, mobile, phoneno, email) values ';
    $query .= "('$fname', '$lname', '$affiliation', '$address1', '$address2', '$city', '$region', '$country', '$mobile', '$phoneno', '$email')";
    $result = db_query($query);
    if (!$result) {
      return false;
    } else {
      $query = "select last_value from win_observer_id_seq";
      $result = db_query($query);
      if (!$result) {
        return false;
      } else {
        if ($arr = db_fetch_object($result)) {
          return $arr->last_value;
        } else {
          return false;
        }
      }
    }
  }
  else { // observer with same email id exists.
    return 'Error: Observer ' . $name . ' with same email id already exists.';
  }
}

function get_current_user_observerid() {
  global $user;
  $id = 0;
  if ($user->uid > 0) {
    $query = 'select mail from drupal_users where uid = ' . $user->uid;
    $result = db_query($query);
    if (!$result) {
    } else {
      if ($obj = db_fetch_object($result)) {
        $mail = $obj->mail;

        $query = "select id from win_observer where email = '{$mail}'";
        $result = db_query($query);
        if (!$result) {
        } else {
          if ($obj = db_fetch_object($result)) {
            $id = $obj->id;
          }
        }
      }
    }
  }

  if ($id == 0) {
    $id = save_current_user_as_observer();
  }
  return $id;
}

function save_current_user_as_observer() {
  global $user;
  if ($user->uid > 0) {
    $details = array();

    $query = 'select mail from drupal_users where uid = ' . $user->uid;
    $result = db_query($query);
    if (!$result) {
      return false;
    } else {
      if ($obj = db_fetch_object($result)) {
        $details['email'] = $obj->mail;
      }
    }

    $query = 'select dpf.name, dpv.value from drupal_profile_fields dpf left outer join drupal_profile_values dpv on dpf.fid = dpv.fid where dpv.uid = ' . $user->uid;
    $result = db_query($query);
    if (!$result) {
      return false;
    } else {
      while ($obj = db_fetch_object($result)) {
        switch ($obj->name) {
          case 'profile_fname':
            $details['fname'] = $obj->value;
            break;
          case 'profile_lname':
            $details['lname'] = $obj->value;
            break;
          case 'profile_affiliation':
            $details['affiliation'] = $obj->value;
            break;
          case 'profile_address1':
            $details['address1'] = $obj->value;
            break;
          case 'profile_address2':
            $details['address2'] = $obj->value;
            break;
          case 'profile_city':
            $details['city'] = $obj->value;
            break;
          case 'profile_region':
            $details['region'] = $obj->value;
            break;
          case 'profile_country':
            $details['country'] = $obj->value;
            break;
          case 'profile_mobile':
            $details['mobile'] = $obj->value;
            break;
          case 'profile_phoneno':
            $details['phoneno'] = $obj->value;
            break;
        }
      }
    }

    return save_observer_details($details);
  }
  return false;
}

function load_observation_for_id($id) {
  if (!is_numeric($id)) {
    return FALSE;
  }
  //$observation = new object();

  $col_info = get_table_columns('win_observations');
  $fields = array();
  foreach ($col_info as $col) {
    $fields[] = $col['name'];
  }
  $key = array_search('topology', $fields);
  $fields[$key] = 'astext(topology) as topology';

  $query = 'select ' . implode(",", $fields) . ' from win_observations where id = ' . $id;
  // $query_args = $arguments;
  // $result = db_query($query, $query_args);
  $result = db_query($query);
  if (!$result) {
    return false;
  }
  else {
    if ($obj = db_fetch_object($result)) {
      $observation = $obj;
    }
  }

  if ($observation == NULL) {
    return FALSE;
  }

  if (!empty($observation->from_date)) {
    $observation->from_date = date('M d, Y', strtotime($observation->from_date));
  }
  if (!empty($observation->to_date)) {
    $observation->to_date = date('M d, Y', strtotime($observation->to_date));
  }
  if (!empty($observation->on_date)) {
    $observation->on_date = date('M d, Y', strtotime($observation->on_date));
  }

  if ($observation->is_exact_time == 0) {
    /*
    $pod_ids = array();
    $query = 'select pod_id from win_observations_partofday where observation_id = ' . $id;
    $result = db_query($query);
    if (!$result) {
      return false;
    }
    else {
      while ($obj = db_fetch_object($result)) {
        $pod_ids[] = $obj->pod_id;
      }
    }
    $observation->pods = implode(',', $pod_ids);
    */

    $pod_ids = array();
    $query = 'select pod.id, pod.label from win_observations_partofday wop join partofday pod on wop.pod_id = pod.id where wop.observation_id = ' . $id;
    // $query_args = $arguments;
    // $result = db_query($query, $query_args);
    $result = db_query($query);
    if (!$result) {
      return false;
    }
    else {
      while ($obj = db_fetch_object($result)) {
        $pod_ids[$obj->id] = $obj->label;
      }
      $observation->pods = $pod_ids;
    }

  }

  if (!empty($observation->at_time)) {
    $observation->at_time = date('h:i a', strtotime($observation->at_time));
  }

  $col_info = get_table_columns('win_common_names');
  $fields = array();
  foreach ($col_info as $col) {
    $fields[] = $col['name'];
  }
  // $key = array_search('observation_id', $fields);
  // unset($fields[$key]);

  $common_names = array();
  $query = 'select ' . implode(",", $fields) . ' from win_common_names where observation_id = ' . $id;
  // $query_args = $arguments;
  // $result = db_query($query, $query_args);
  $result = db_query($query);
  if (!$result) {
    return false;
  }
  else {
    while ($obj = db_fetch_array($result)) {
      $common_names[] = $obj;
    }
  }

  $observation->common_names = $common_names;

  $col_info = get_table_columns('win_scientific_name');
  $fields = array();
  foreach ($col_info as $col) {
    $fields[] = $col['name'];
  }

  $scientific_name_info = array();
  $query = 'select ' . implode(",", $fields) . ' from win_scientific_name where observation_id = ' . $id;
  // $query_args = $arguments;
  // $result = db_query($query, $query_args);
  $result = db_query($query);
  if (!$result) {
    return false;
  }
  else {
    if ($obj = db_fetch_object($result)) {
      $scientific_name_info['s_name'] = $obj->s_name;
      $scientific_name_info['s_author'] = $obj->s_author;
      $scientific_name_info['s_year'] = $obj->s_year;
    }
    else {
      $scientific_name_info['s_name'] = '';
      $scientific_name_info['s_name'] = '';
      $scientific_name_info['s_name'] = '';
    }
  }

  $observation->scientific_name_info = $scientific_name_info;

  $col_info = get_table_columns('win_observation_location');
  $fields = array();
  foreach ($col_info as $col) {
    $fields[] = $col['name'];
  }
  // $key = array_search('observation_id', $fields);
  // unset($fields[$key]);
  // $key = array_search('id', $fields);
  // unset($fields[$key]);

  $query = 'select ' . implode(",", $fields) . ' from win_observation_location where observation_id = ' . $id;
  // $query_args = $arguments;
  // $result = db_query($query, $query_args);
  $result = db_query($query);
  if (!$result) {
    return false;
  }
  else {
    if ($obj = db_fetch_array($result)) {
      $observation->location = $obj;
    }
  }

  $observer_id = $observation->observer_id;
  unset($observation->observer_id);

  if ($observer_id) {
    $query = 'select * from win_observer where id = ' . $observer_id;
    // $query_args = $arguments;
    // $result = db_query($query, $query_args);
    $result = db_query($query);
    if (!$result) {
      return false;
    }
    else {
      if ($obj = db_fetch_array($result)) {
        $observation->observer = $obj;
      }
    }
  }

  // validation information
  $validation = array();
  $query = 'select * from win_validation where observation_id = %d';
  $query_args = array($id);
  $result = db_query($query, $query_args);
  if (!$result) {
  }
  else {
    $status = array('Pending', 'Approved', 'Rejected');
    while ($obj = db_fetch_object($result)) {
      $validation[] = array('status' => $status[$obj->status], 'comments' => $obj->comments, 'validated_by' => get_user_name($obj->validated_by), 'validated_by_id' => $obj->validated_by, 'validated_date' => date('M d, Y', strtotime($obj->validated_date)));
    }
  }
  $observation->validation = $validation;

  return $observation;
}

function get_table_columns($tablename, $get_desc = FALSE, $get_type = FALSE) {
  $columns = array();

  global $db_url;
  $url = parse_url($db_url);
  $db_name = str_replace("/", "", $url['path']);

  $data_type = '';
  if ($get_type) {
    $data_type = ', data_type';
  }

  $desc = '';
  if ($get_desc) {
    $desc = ', description';
  }

  //$query = "select column_name {$data_type} from information_schema.columns where table_catalog = '{$db_name}' and table_name = '{$tablename}'";
  $query = "select column_name {$data_type} {$desc} from win_observations_schema_info_view where table_name = '{$tablename}'";
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    $i = 0;
    while ($obj = db_fetch_object($result)) {
      $columns[$i]['name'] = $obj->column_name;
      if ($get_type) {
        $columns[$i]['type'] = $obj->data_type;
      }
      if ($get_desc) {
        $columns[$i]['description'] = $obj->description;
      }

      $i++;

      /*
      if ($prepend_tablename) {
        if ($get_type) {
          $columns[$tablename . '.' . $obj->column_name] = $obj->data_type;
        } else {
          $columns[] = $tablename . '.' . $obj->column_name;
        }
      }
      else {
        if ($get_type) {
          $columns[$obj->column_name] = $obj->data_type;
        }
        elseif if ($get_desc) {
          $columns[$obj->column_name] = $obj->description;
        }
        else {
          $columns[] = $obj->column_name;
        }
      }
      */
    }
  }
  return $columns;
}

function upload_image($params) {
  global $user;
  if (!win_observation_user_has_edit_permissions()) {
    die(json_encode(set_error_arr("You are not authorized.")));
  }

  $fileElem = $params['fileElem'];
  $observation_id = $params['observation_id'];
  $copyright_text = $params['copyright_text'];

  $_FILESinfo = $_FILES[$fileElem];

  $files_len = 1;
  if (is_array($_FILESinfo['name'])) {
    $files_len = count($_FILESinfo['name']);
  }

  $atlst1File = false;
  $empty_files = array();
  $err = array();
  if ($files_len == 1) {
    $error_arr = array($_FILESinfo["error"]);
  }
  else {
    $error_arr = $_FILESinfo["error"];
  }
  $size_error = array();
  $len = count($error_arr);
  for($i = 0; $i < $len; $i++) {
    if ($error_arr[$i] == UPLOAD_ERR_OK) {
      $atlst1File = true;
    }
    elseif ($error_arr[$i] == UPLOAD_ERR_NO_FILE) { // File may not be uploaded in remaining inputs.
      $empty_files[] = $i;
    }
    elseif ($error_arr[$i] == UPLOAD_ERR_INI_SIZE) {
      $size_error[] = $i + 1;
    }
    else {
      $err[] = $i + 1;
    }
  }

  if (count($size_error) > 0) {
    die(json_encode(set_error_arr("File size is large for files: " . implode(',', $size_error) . ini_get('max_upload_filesize'))));
  }

  if (count($err) > 0) {
    die(json_encode(set_error_arr("File upload error for nums: " . implode(',', $err))));
  }

  if (!$atlst1File) {
    die(json_encode(set_error_arr("No file specified.")));
  }

  $err = array();
  if ($files_len == 1) {
    $type_arr = array($_FILESinfo["type"]);
  }
  else {
    $type_arr = $_FILESinfo["type"];
  }
  $len = count($type_arr);
  for($i = 0; $i < $len; $i++) {
    if (!in_array($i, $empty_files)) { // ignore empty files
      if (strpos($type_arr[$i], 'image') !== 0) {
        $err[] = $i + 1;
      }
    }
  }

  if (count($err) > 0) {
    die(json_encode(set_error_arr("Only image type files are supported. Check file nums: " . implode(',', $err))));
  }

  // get the local path on the machine
  $uploadpath = dirname(realpath('index.php')) . '/sites/default/files/images/uploads/';

  if (!is_dir($uploadpath)) {
    mkdir($uploadpath, 0777, TRUE);
  }

  if (!is_dir($uploadpath.$user->name)) {
    mkdir($uploadpath.$user->name, 0777, TRUE);
  }

  $err = array();
  if ($files_len == 1) {
    $name_arr = array($_FILESinfo["name"]);
    $tmp_name_arr = array($_FILESinfo["tmp_name"]);
  }
  else {
    $name_arr = $_FILESinfo["name"];
    $tmp_name_arr = $_FILESinfo["tmp_name"];
  }

  $len = count($name_arr);
  for ($i = 0; $i < $len; $i++) {
    if (!in_array($i, $empty_files)) {
      $uniqid = uniqid();

      $name = str_replace("'", "", $name_arr[$i]);
      $name = str_replace(" ", "_", $name);

      $fname = $user->name . '/' . $uniqid . '_' . $name;
      $indx = strripos($fname, '.');
      $orig_fname = substr($fname, 0, $indx) . '_orig' . substr($fname, $indx);
      $tn_fname = substr($fname, 0, $indx) . '_tn' . substr($fname, $indx);
      $watermarkFileName = $uploadpath . $fname;
      // $indx = strripos($watermarkFileName, '.');
      // $newFileName = substr($watermarkFileName, 0, $indx) . '_orig' . substr($watermarkFileName, $indx);
      $newFileName = $uploadpath . $orig_fname;
      $tnFileName = $uploadpath . $tn_fname;

      move_uploaded_file($tmp_name_arr[$i], $newFileName);

      include_once('image_manipulation.inc');
      watermarkImage($newFileName, $copyright_text, $watermarkFileName, 50, 20);
      createImageThumbnail($newFileName, $tnFileName);

      if (!save_observation_image_mapping($observation_id, $orig_fname, $fname, $tn_fname, $copyright_text)) {
        //die(json_encode(set_error_arr("Error saving file on server.")));
        $err[] = $i + 1;
      }
      else {
        /*
        $msg = 'File has been uploaded successfully.';
        display_message('status', t($msg));
        die(json_encode(set_no_error_arr($msg)));
        */
	      $imgs_url = base_path() . 'observation/'.$observation_id.'/images';
        $rec_url = base_path() . 'observation/add';
        if ($files_len == 1) {
          display_message('status', t('Thank you for contributing to Spandan. Your data still needs to be validated and marked as verfied. It will be displayed only after validation. To upload more images click <a href="'.$imgs_url.'">here</a> OR click <a href="'.$rec_url.'">here</a> to contribute more records.'));
        }
      }
    }
  }
  if (count($err) > 0) {
    $len_err = count($err);
    $len_total = count($name_arr);
    $len_empty = count($empty_files);
    if ($len_arr == ($len_total - $len_empty)) { // All files failed
      die(json_encode(set_error_arr("Error saving file on server.")));
    }
    else {
      $msg = 'File(s) uploaded successfully except num: ' . implode(', ', $err);
      display_message('status', t($msg));
      die(json_encode(set_no_error_arr($msg)));
    }
  }
  else {
    $msg = 'File(s) uploaded successfully.';
    if ($files_len > 1) {
      display_message('status', t($msg));
    }
    die(json_encode(set_no_error_arr($msg)));
  }
}

function delete_image($params) {
  global $user;
  if (!win_observation_user_has_edit_permissions()) {
    die(json_encode(set_error_arr("You are not authorized.")));
  }

  $oid = $params['oid'];
  $img_id = $params['img_id'];

  $orig_image = '';
  $wm_image = '';
  $tn_image = '';
  $query = 'select orig_image, wm_image, tn_image from win_observation_images where observation_id = %d and id = %d';
  $query_args = array($oid, $img_id);
  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr('Error talking to database')));
  }
  else {
    if ($obj = db_fetch_object($result)) {
      $orig_image = $obj->orig_image;
      $wm_image = $obj->wm_image;
      $tn_image = $obj->tn_image;

      $query = 'delete from win_observation_images where observation_id = %d and id = %d';
      $query_args = array($oid, $img_id);
      $result = db_query($query, $query_args);
      if (!$result) {
        die(json_encode(set_error_arr('Error talking to database')));
      }
      else {
        $uploadpath = dirname(realpath('index.php')) . '/sites/default/files/images/uploads/';

        unlink($uploadpath.$orig_image);
        unlink($uploadpath.$wm_image);
        unlink($uploadpath.$tn_image);

        die(json_encode(set_no_error_arr('')));
      }
    }
  }

  die(json_encode(set_error_arr('Error: Please try again later.')));
}

function clear_observation_image_mapping($oid) {
  $query = 'delete from win_observation_images where observation_id = %d';
  $query_args = array($oid);
  $result = db_query($query, $query_args);
  if (!$result) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

function save_observation_image_mapping($observation_id, $filename, $wm_filename, $tn_filename, $copyright_text = '') {
  $query = 'insert into win_observation_images (observation_id, orig_image, wm_image, tn_image, copyright_text) ';
  $query .= "values(%d, '%s', '%s', '%s', '%s')";
  $query_args = array($observation_id, $filename, $wm_filename, $tn_filename, $copyright_text);
  $result = db_query($query, $query_args);
  if (!$result) {
    return false;
  }
  else {
    return true;
  }
}

function get_observation_image_thumbnail_names($observation_id) {
  $tn_images = array();
  $query = 'select tn_image from win_observation_images where observation_id = ' . $observation_id;
  $result = db_query($query);
  if (!$result) {
    return false;
  }
  else {
    while ($obj = db_fetch_object($result)) {
      $tn_images[] = $obj->tn_image;
    }
    return $tn_images;
  }
  return FALSE;
}

function get_observation_watermarked_image_names($observation_id) {
  $tn_images = array();
  $query = 'select wm_image from win_observation_images where observation_id = ' . $observation_id;
  $result = db_query($query);
  if (!$result) {
    return false;
  }
  else {
    while ($obj = db_fetch_object($result)) {
      $tn_images[] = $obj->wm_image;
    }
    return $tn_images;
  }
  return FALSE;
}

function get_observation_image_names($observation_id, $limit = NULL) {
  $images = array();
  $query = 'select id, wm_image, tn_image from win_observation_images where observation_id = ' . $observation_id;
  if ($limit == NULL) {
    $result = db_query($query);
  }
  else {
    $result = db_query_range($query, 0, (int)$limit);
  }
  if (!$result) {
    return false;
  }
  else {
    $i = 0;
    while ($obj = db_fetch_object($result)) {
      /*
      $images['id'][] = $obj->id;
      $images['wm'][] = $obj->wm_image;
      $images['tn'][] = $obj->tn_image;
      */
      $images[$i]['id'] = $obj->id;
      $images[$i]['wm'] = $obj->wm_image;
      $images[$i]['tn'] = $obj->tn_image;
      $i++;
    }
    return $images;
  }
  return FALSE;
}

function _escape_accidental_placeholders_from_Drupal($str) {
  /* Drupal tries to replace placeholders even when no args
   * have been specified. This cause problems in case where
   * you are trying to make a query similar to "where val
   * like ('%fu')" etc. Drupal tries to escape (%d|%s|%%|%f|%b|%n)
   */

  $esc_arr = array('d', 's', 'f', 'b', 'n');
  $arr = explode('%', $str);
  $len = count($arr);
  for ($i = 0; $i < $len; $i++) {
    if (in_array($arr[$i][0], $esc_arr)) {
      $arr[$i] = '%' . $arr[$i];
    }
  }

  return implode('%', $arr);
}

function _return_simple_search_results($srchStr, $query, $tablename, $id_col, $col_names) {
  $field_keys = array_keys($col_names);
  $query_where = array();
  $esc_str = _escape_accidental_placeholders_from_Drupal(db_escape_string($srchStr));
  foreach ($field_keys as $field) {
    $query_where[] = "lower({$field}) like '%" . $esc_str . "%'";
  }

  $query = "select {$id_col}, " . implode(",", $field_keys) . " from {$tablename} where " . implode(' or ', $query_where) . ";";

  $srch_results = array();
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  } else {
    $i = 0;
    while ($obj = db_fetch_object($result)) {
      $srch_results[$i]['match'] = '';
      foreach ($obj as $key => $value) {
        switch ($key) {
          case $id_col:
            $srch_results[$i]['id'] = $obj->{$key};
          break;
          default:
            if (!empty($value)) {
              if (strpos(strtolower($value), strtolower($srchStr)) !== FALSE) {
                $srch_results[$i]['match'] .= '<b>' . (!empty($col_names[$key]) ? $col_names[$key] : $key) . "</b>: $value<br>";
              }
            }
            break;
        }
      }
      $i++;
    }

    return $srch_results;
  }
}

function get_col_autocomplete_values($params) {
  $type = $params['type'];
}

function set_error_arr($msg) {
  return array("error" => "1", "msg" => t($msg));
}

function set_no_error_arr($msg) {
  return array("error" => "0", "msg" => t($msg));
}

function get_query_values_holder($arr) {
  $arr_str = array();
  $len = count($arr);
  for ($i = 0; $i < $len; $i++) {
    $arr_str[] = "'%s'";
  }
  return implode(', ', $arr_str);
}

function win_observation_user_has_edit_permissions() {
  if (user_access('create win_observation content') || user_access('edit own win_observation content') || user_access('edit any win_observation content')) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

function display_message($type, $message) {
  $_SESSION['messages'][$type][] = $message;
}

function get_user_name($userid){
  $res = db_fetch_array(db_query("select name from {users} where uid = %d", $userid));
  $name = $res['name'];

  $fname = '';
  $lname = '';
  $query = "select dpf.name, dpv.value from drupal_profile_fields dpf left outer join drupal_profile_values dpv on dpf.fid = dpv.fid where dpf.name in ('profile_fname', 'profile_lname') and dpv.uid = " . $userid;
  $result = db_query($query);
  if (!$result) {
    return false;
  } else {
    while ($obj = db_fetch_object($result)) {
      switch ($obj->name) {
        case 'profile_fname':
          $fname = $obj->value;
        break;
        case 'profile_lname':
          $lname = $obj->value;
        break;
      }
    }
  }

  $fullname = "$fname $lname";

  $usernamelnk = '<a href="' . base_path() . 'user/' . $userid . '">' . $name . '</a>';
  if (empty($fullname)) {
    return $usernamelnk;
  }
  else {
    return $fullname . '(' . $usernamelnk . ')';
  }
}

function is_user_validator() {
  global $user;
  if ($user->uid > 0) {
    if ($user->uid == 1) {
      return TRUE;
    }

    $query = 'select count(*) as count from win_validators where uid = %d and status = 1';
    $query_args = array($user->uid);
    $result = db_query($query, $query_args);
    if (!$result) {
      return FALSE;
    }
    else {
      if ($obj = db_fetch_object($result)) {
        if ($obj->count) {
          return TRUE;
        }
      }
    }
  }
  return FALSE;
}

function can_user_validate_observation($observation) {
  if (is_user_validator()) {
    //global $user;
    //if ($user->uid != $observation->created_by) {
      return TRUE;
    //}
  }
  return FALSE;
}

function get_common_name_languages() {
  $query = 'select cn_language from win_cn_languages order by cn_language';
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    $languages = array();
    while($obj = db_fetch_object($result)) {
      $languages[] = $obj->cn_language;
    }

    return $languages;
  }
}

function get_basis_of_record_list() {
  $query = 'select bor_name from win_basis_of_record order by bor_name';
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    $bor = array();
    array_push($bor,'');
    array_push($bor,'not sure');
    while($obj = db_fetch_object($result)) {
      $bor[] = $obj->bor_name;
    }

    return $bor;
  }
}

function get_taxanomic_status_list() {
  $query = 'select ts_name from win_taxonomic_status order by ts_name';
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    $ts = array();
    array_push($ts,'');
    while($obj = db_fetch_object($result)) {
      $ts[] = $obj->ts_name;
    }

    return $ts;
  }
}

function get_nomenclature_type_status_list() {
  $query = 'select nts_name from win_nomenclature_type_status order by nts_name';
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    $nts = array();
    array_push($nts,'');
    while($obj = db_fetch_object($result)) {
      $nts[] = $obj->nts_name;
    }

    return $nts;
  }
}

function get_nativeness_list() {
  $query = 'select en_name from win_ecosystem_nativeness order by en_name';
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    $nativeness = array();
    array_push($nativeness,'');
    while($obj = db_fetch_object($result)) {
      $nativeness[] = $obj->en_name;
    }

    return $nativeness;
  }
}

function get_iucn_threat_category_list() {
  $query = 'select tc_name from win_iucn_threat_category order by tc_name';
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    $threat_cat = array();
    array_push($threat_cat,'');
    while($obj = db_fetch_object($result)) {
      $threat_cat[] = $obj->tc_name;
    }

    return $threat_cat;
  }
}

function get_observation_info_for_search_results($oids) {
  $observations = array();
  if (count($oids) > 0) {
    $oids_str = implode(', ', $oids);

    $query = <<<EOT
    SELECT
      wo.id,
      wsn.s_name AS scientific_name,
      wol.locality,
      wol.country,
      CASE WHEN wo.is_waterbody_related = 0 THEN '' ELSE wo.waterbody_type || ': ' || wo.waterbody_name END AS waterbody,
      wo.created_by,
      CASE WHEN wo.is_date_range = 0 THEN to_char(wo.on_date, 'Mon DD, YYYY') ELSE to_char(wo.from_date, 'Mon DD, YYYY') || ' to ' || to_char(wo.to_date, 'Mon DD, YYYY') END AS observation_date
    FROM win_observations wo LEFT JOIN win_scientific_name wsn ON wo.id = wsn.observation_id
    LEFT JOIN win_observation_location wol ON wo.id = wol.observation_id
    WHERE wo.id IN ({$oids_str});
EOT;
    $result = db_query($query);
    if (!$result) {
      return FALSE;
    }
    else {
      while ($obj = db_fetch_object($result)) {
        foreach ($obj as $key => $val) {
          switch ($key) {
            case 'id':
              break;
            case 'created_by':
              $observations[$obj->id]['contributor'] = get_user_name($val);
              break;
            default:
              $observations[$obj->id][$key] = $val;
              break;
          }
        }
      }
    }

    $query = "select observation_id, common_name || '(' || cn_language || ')' as common_name from win_common_names where observation_id in ({$oids_str})";
    $result = db_query($query);
    if (!$result) {
      return FALSE;
    }
    else {
      while ($obj = db_fetch_object($result)) {
        foreach ($obj as $key => $val) {
          switch ($key) {
            case 'observation_id':
              break;
            case 'common_name':
              $observations[$obj->observation_id]['common_name'][] = $val;
              break;
          }
        }
      }
    }
  }

  return $observations;
}

function show_search_results($observations, $show_validate = FALSE) {
  $html = '';
  $html .= <<<EOT
    <table class="search_results">
      <thead>
        <tr>
          <th>No.</th>
          <th>View</th>
EOT;
  if ($show_validate === TRUE) {
    $html .= '<th>Validate</th>';
  }
  $html .= <<<EOT
          <th>Common Name</th>
          <th>Scientific Name</th>
          <th>Locality</th>
          <th>Country</th>
          <th>Waterbody</th>
          <th>Countributor</th>
          <th>Observation Date</th>
        </tr>
      </thead>
      <tbody>
EOT;
  $i = 1;
  if (is_array($observations)) {
    foreach ($observations as $id => $info) {
      $ob_lnk = base_path().'observation/'.$id;
      $common_name = '';
      if (count($info['common_name']) == 0) {
        $common_name = '&nbsp;';
      }
      else {
        $names_info = array();
        foreach ($info['common_name'] as $cn) {

          $names_info[] = $cn;
        }
        $common_name .= implode('<br />', $names_info);
      }
      $scientific_name = (empty($info['scientific_name']) ? '&nbsp;' : $info['scientific_name']);
      $locality = (empty($info['locality']) ? '&nbsp;' : $info['locality']);
      $country = (empty($info['country']) ? '&nbsp;' : $info['country']);
      $waterbody = (empty($info['waterbody']) ? '&nbsp;' : $info['waterbody']);
      $contributor = (empty($info['contributor']) ? '&nbsp;' : $info['contributor']);
      $date = (empty($info['observation_date']) ? '&nbsp;' : $info['observation_date']);
      $html .= <<<EOT
          <tr>
            <td>{$i}</td>
            <td><a href="{$ob_lnk}" target="_blank">View</a></td>
EOT;
      if ($show_validate === TRUE) {
        $html .= '<td><a href="' . $ob_lnk . '/validate" target="_blank">Validate</a></td>';
      }
      $html .= <<<EOT
            <td>{$common_name}</td>
            <td>{$scientific_name}</td>
            <td>{$locality}</td>
            <td>{$country}</td>
            <td>{$waterbody}</td>
            <td>{$contributor}</td>
            <td>{$date}</td>
          </tr>
EOT;
      $i++;
    }
  }
  $html .= <<<EOT
      </tbody>
    </table>
EOT;
  return $html;
}

function get_current_db_name() {
  global $db_url;
  $url = parse_url(is_array($db_url) ? $db_url['default'] : $db_url);
  $db_path = ltrim(urldecode($url['path']), '/');

  return $db_path;
}

function get_preview_images_html($observation_id) {
  $path = drupal_get_path('module','win_observation');
  drupal_add_js($path . '/js/external/jquery-1.3.2.js');
  //drupal_add_js($path . '/js/external/jquery.galleria.js');
  //drupal_add_css($path . '/css/jquery.galleria.css');
  drupal_add_js($path . '/js/external/ui.core.js');
  drupal_add_js($path . '/js/external/ui.draggable.js');
  drupal_add_js($path . '/js/external/ui.resizable.js');
  drupal_add_js($path . '/js/external/ui.dialog.js');
  drupal_add_js($path . '/js/win_observation_images.js');

  drupal_add_css($path . '/css/jquery-ui.css');
  drupal_add_css($path. '/css/win_observation_images.css');

  $imgs = get_observation_image_names($observation_id, 4);

  $html = '<div id="previewUploadedImages">';
  $html .= '<div>';

  $len = count($imgs);
  if ($len > 0) {
    $path = base_path() . 'sites/default/files/images/uploads/';
    //$html .= '<ul class="gallery">';
    for ($i = 0; $i < $len; $i++) {
      $img = $imgs[$i];
      $src = $path . $img['tn'];
      $imgurl = $path . $img['wm'];
      //$html .= '<li><img src="'.$src.'" />';
      $html .= '<div class="galImgBox" onclick="showImage(\''.$imgurl.'\')"><img src="'.$src.'" /></div>';
    }
    //$html .= '</ul>';
  }
  else {
    $html .= 'No images have been uploaded yet.';
  }

  $html .= '</div>';
  $html .= '<div style="text-align: center; float: left; width: 100%; padding: 10px; background-color: #EEEEEE;">';
  $html .= '<a href="'.base_path().'observation/'.$observation_id.'/images" target="_blank">View more images</a>';
  $html .= '</div>';
  $html .= '</div>';

  $html .= '<div id="div_win_observation_image"><img id="win_observation_image" src="" alt="" /></div>';

  return $html;
}

function get_win_statistics() {
  $query = 'SELECT num_contributors, num_contributor_countries, num_contributions, num_validated_contributions, num_experts, num_expert_countries FROM win_observation_statistics_view;';
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  }
  else {
    if ($arr = db_fetch_array($result)) {
      return $arr;
    }
  }
}

function is_observation_validated($oid) {
  $query = 'select count(id) as count from win_validation where status = 1 and observation_id = %d';
  $query_args = array($oid);
  $result = db_query($query, $query_args);
  if (!$result) {
    return FALSE;
  }
  else {
    if ($obj = db_fetch_object($result)) {
      if ($obj->count > 0) {
        return TRUE;
      }
      else {
        return FALSE;
      }
    }
  }
  return FALSE;
}